<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="motan,源码,client,异步消息" />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="如何设计RPC异步消息？异步调用的好处就不说了，我们直入主题，讨论RPC异步消息如何设计？ 既然是异步的，我们有一个首要的问题需要解决：  通常异步调用都是一问一答的模式，一个Request拿到一个Response，如果我们做了异步，怎么把这两个消息对应起来呢？  既然需要对应，那么只有一种思路就是通过一种方式把两者联系起来，所以我们在设计协议的时候必须包含一个messageID，唯一的，这个唯一">
<meta name="keywords" content="motan,源码,client,异步消息">
<meta property="og:type" content="article">
<meta property="og:title" content="Motan源码解读-Client异步消息">
<meta property="og:url" content="http://www.zhizus.com/2016-09-19-motan-clientMessage.html">
<meta property="og:site_name" content="郑大侠的博客">
<meta property="og:description" content="如何设计RPC异步消息？异步调用的好处就不说了，我们直入主题，讨论RPC异步消息如何设计？ 既然是异步的，我们有一个首要的问题需要解决：  通常异步调用都是一问一答的模式，一个Request拿到一个Response，如果我们做了异步，怎么把这两个消息对应起来呢？  既然需要对应，那么只有一种思路就是通过一种方式把两者联系起来，所以我们在设计协议的时候必须包含一个messageID，唯一的，这个唯一">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-06-04T02:56:46.712Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Motan源码解读-Client异步消息">
<meta name="twitter:description" content="如何设计RPC异步消息？异步调用的好处就不说了，我们直入主题，讨论RPC异步消息如何设计？ 既然是异步的，我们有一个首要的问题需要解决：  通常异步调用都是一问一答的模式，一个Request拿到一个Response，如果我们做了异步，怎么把这两个消息对应起来呢？  既然需要对应，那么只有一种思路就是通过一种方式把两者联系起来，所以我们在设计协议的时候必须包含一个messageID，唯一的，这个唯一">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: "",
      labels: ""
    }
  };
</script>



  <link rel="canonical" href="http://www.zhizus.com/2016-09-19-motan-clientMessage.html"/>





  <title> Motan源码解读-Client异步消息 | 郑大侠的博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?f75c9cec9ecead0dfce9a108b9688072";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">郑大侠的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-crossed">
          <a href="http://zhizus.com" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-camera-retro"></i> <br />
            
            穿越
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://www.zhizus.com/2016-09-19-motan-clientMessage.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="DempeZheng">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/6263631?v=3&s=466">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="郑大侠的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Motan源码解读-Client异步消息
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            

            

            
          </span>

          

          
            
          

          
          
             <span id="/2016-09-19-motan-clientMessage.html" class="leancloud_visitors" data-flag-title="Motan源码解读-Client异步消息">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="如何设计RPC异步消息？"><a href="#如何设计RPC异步消息？" class="headerlink" title="如何设计RPC异步消息？"></a>如何设计RPC异步消息？</h2><p>异步调用的好处就不说了，我们直入主题，讨论RPC异步消息如何设计？</p>
<p>既然是异步的，我们有一个首要的问题需要解决：</p>
<blockquote>
<p>通常异步调用都是一问一答的模式，一个Request拿到一个Response，如果我们做了异步，怎么把这两个消息对应起来呢？</p>
</blockquote>
<p>既然需要对应，那么只有一种思路就是通过一种方式把两者联系起来，所以我们在设计协议的时候必须包含一个messageID，唯一的，这个唯一性是在客户端维护（多是自增）。</p>
<p>客户端发送请求的req的时候，先req.setMessageId(messageID)，然后在发送；服务端拿到这个messageID的时候，把messageID原封不动的包装在Response中，这样客户端就可以把request和response对应起来。</p>
<h2 id="纸上得来终觉浅，我们试着来撸一个"><a href="#纸上得来终觉浅，我们试着来撸一个" class="headerlink" title="纸上得来终觉浅，我们试着来撸一个"></a>纸上得来终觉浅，我们试着来撸一个</h2><p>我们写一个简单的DefaultClient</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DefaultClient</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">protected</span> Map&lt;Integer, Context&gt; contextMap = <span class="keyword">new</span> ConcurrentHashMap&lt;Integer, Context&gt;();</span><br><span class="line">  </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">initClientChannel</span><span class="params">(SocketChannel ch)</span> </span>&#123;</span><br><span class="line">        ChannelPipeline pipeline = ch.pipeline();</span><br><span class="line">        pipeline.</span><br><span class="line">                .addLast(<span class="string">"ClientHandler"</span>, <span class="keyword">new</span> ChannelHandlerAdapter() &#123;</span><br><span class="line">                    <span class="comment">/**</span></span><br><span class="line"><span class="comment">                    * 收到服务端消息</span></span><br><span class="line"><span class="comment">                    **/</span></span><br><span class="line">                    <span class="meta">@Override</span></span><br><span class="line">                    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelRead</span><span class="params">(ChannelHandlerContext ctx, Response resp)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">                    </span><br><span class="line">                        <span class="comment">// 收到服务端消息，找出对应包含context的request上下文，然后移除</span></span><br><span class="line">                        Context context = contextMap.remove(id);</span><br><span class="line">                        <span class="keyword">if</span> (context == <span class="keyword">null</span>) &#123;</span><br><span class="line">                            LOGGER.debug(<span class="string">"messageID:&#123;&#125;, take Context null"</span>, id);</span><br><span class="line">                            <span class="keyword">return</span>;</span><br><span class="line">                        &#125;</span><br><span class="line">                        <span class="comment">//异步通知结果返回</span></span><br><span class="line">                        context.cb.onReceive(resp);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 发送消息，并等待Response</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> request</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> Response</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Callback <span class="title">call</span><span class="params">(Request request, Callback callback)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> id = getNextMessageId();</span><br><span class="line">        request.setMessageID(id);</span><br><span class="line">        Context context = <span class="keyword">new</span> Context(id, request, callback);</span><br><span class="line">        <span class="comment">// 发送消息前先把request上下文保存起来，</span></span><br><span class="line">        contextMap.put(id, context);</span><br><span class="line">        writeAndFlush(request);</span><br><span class="line">        <span class="comment">// 消息发送出去就直接返回callback，不会阻塞等待服务端结果返回</span></span><br><span class="line">        <span class="comment">// 当客户端收到服务端返回的response首先会通过messageID找到对应的request上下文，然后调用callback的onReceive(resp)方法通知</span></span><br><span class="line">        <span class="keyword">return</span> callback;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Future&lt;Response&gt; <span class="title">send</span><span class="params">(Request request)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        Promise&lt;Response&gt; future = <span class="keyword">new</span> Promise&lt;Response&gt;();</span><br><span class="line">        call(request, future);</span><br><span class="line">        <span class="keyword">return</span> future;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Response <span class="title">sendAnWait</span><span class="params">(Request request)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        Future&lt;Response&gt; future = send(request);</span><br><span class="line">        <span class="keyword">return</span> future.await();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Response <span class="title">sendAnWait</span><span class="params">(Request request, <span class="keyword">long</span> amount, TimeUnit unit)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        Future&lt;Response&gt; future = send(request);</span><br><span class="line">        <span class="keyword">return</span> future.await(amount, unit);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Context</span> </span>&#123;</span><br><span class="line">        <span class="keyword">final</span> Request request;</span><br><span class="line">        <span class="keyword">final</span> Callback cb;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">short</span> id;</span><br><span class="line"></span><br><span class="line">        Context(<span class="keyword">short</span> id, Request request, Callback cb) &#123;</span><br><span class="line">            <span class="keyword">this</span>.id = id;</span><br><span class="line">            <span class="keyword">this</span>.cb = cb;</span><br><span class="line">            <span class="keyword">this</span>.request = request;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>DefaultClient做的事情就是在发送Request消息时候先保存request的上下文，等到服务端消息返回，然后通过callback异步通知。
接下来我们要看看callback的实现了：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Promise</span>&lt;<span class="title">T</span>&gt; <span class="keyword">implements</span> <span class="title">Callback</span>&lt;<span class="title">T</span>&gt;, <span class="title">Future</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> CountDownLatch latch = <span class="keyword">new</span> CountDownLatch(<span class="number">1</span>);</span><br><span class="line">    Throwable error;</span><br><span class="line">    <span class="keyword">private</span> T message;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onReceive</span><span class="params">(T message)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">            <span class="keyword">this</span>.message = message;</span><br><span class="line">            latch.countDown();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 当onReceive调用之前，await方法会阻塞，一直到timeout</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">await</span><span class="params">(<span class="keyword">long</span> amount, TimeUnit unit)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (latch.await(amount, unit)) &#123;</span><br><span class="line">            <span class="keyword">return</span> get();</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> TimeoutException();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">await</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        latch.await();</span><br><span class="line">        <span class="keyword">return</span> get();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> T <span class="title">get</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        Throwable e = error;</span><br><span class="line">        <span class="keyword">if</span> (e != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (e <span class="keyword">instanceof</span> RuntimeException) &#123;</span><br><span class="line">                <span class="keyword">throw</span> (RuntimeException) e;</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (e <span class="keyword">instanceof</span> Exception) &#123;</span><br><span class="line">                <span class="keyword">throw</span> (Exception) e;</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (e <span class="keyword">instanceof</span> Error) &#123;</span><br><span class="line">                <span class="keyword">throw</span> (Error) e;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">// don'M expect to hit this case.</span></span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> message;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>利用java的CountDownLatch可以非常轻松的实现：当回调方法调用之前，获取结果的await方法一直阻塞的。</p>
<p>到此为止，我们基本实现异步消息调用的核心<code>伪代码</code>，但是是不是万事大吉了呢？</p>
<h2 id="But，还有一个大bug"><a href="#But，还有一个大bug" class="headerlink" title="But，还有一个大bug"></a>But，还有一个大bug</h2><p>还有什么问题？</p>
<blockquote>
<p>服务端异常状态没有机制返回给客户端？</p>
</blockquote>
<p>当然这个也是一个很严重的问题，但是只能算是一个需要优化的地方，并不是下面要说的大bug。</p>
<p><strong>我们思考一下下面的问题：</strong></p>
<ul>
<li>1.客户端发送异常的时候，contextMap中存储的Request上下文如何回收？</li>
<li>2.服务端超时或者异常情况，contextMap又如何回收？</li>
</ul>
<p>问题1很要解决，在发送的时候捕获一下发送的异常，出现异常主动将contextMap的对象移除。伪代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Callback <span class="title">call</span><span class="params">(Request request, Callback callback)</span>  </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> id = getNextMessageId();</span><br><span class="line">    request.setMessageID(id);</span><br><span class="line">    Context context = <span class="keyword">new</span> Context(id, request, callback);</span><br><span class="line">    <span class="comment">// 发送消息前先把request上下文保存起来，</span></span><br><span class="line">    contextMap.put(id, context);</span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">         writeAndFlush(request);</span><br><span class="line">    &#125;<span class="keyword">catch</span>(Exception e)&#123;</span><br><span class="line">         contextMap.remove(id);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 消息发送出去就直接返回callback，不会阻塞等待服务端结果返回</span></span><br><span class="line">    <span class="comment">// 当客户端收到服务端返回的response首先会通过messageID找到对应的request上下文，然后调用callback的onReceive(resp)方法通知</span></span><br><span class="line">    <span class="keyword">return</span> callback;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>关键是问题2，服务端超时，或者异常，这时候客户端收不到任何消息，那么上面的代码中contextMap的request上下文就没办法清理掉。</p>
<p>这个时候该如何处理呢？
我们先讨论RPC一个很重的点：<code>TimeOut机制</code>。
如果没有timeout，假设某个服务响应慢或者不可用，可能造成客户端所有的connection都在等待请求响应，其他可用的服务也无法提供服务。
客户端请求分配的资源是有限的，我们不能因为某个业务不可用或者响应慢而让他占用了所有的资源。<code>对于每个异步调用的请求，我们最好都能给他一个默认的超时时间</code>。</p>
<p>既然RPC有timeout机制，那么处理问题2最自然的思路就是定时去扫描contextMap，将里面超时的context清理掉。<code>motan也是这么做的</code></p>
<p>不过，我们还有其他的办法：</p>
<p>我们在客户端发送请求前，先通过<code>timer.newTimeout(new ClearContextMapTask(){},....)</code>,等到这个连接超时，就会自动执行这个ClearContextMapTask，clean对应的超时request上下文。
这个还没完，因为很多时候，消息能够正常返回，<code>正常返回的时候我们主动将这个任务cancel掉</code>。</p>
<p>具体的实现可以参考<a href="https://github.com/Baidu-ecom/Jprotobuf-rpc-socket，（貌似是百度出品，代码质量还是有保障的）" target="_blank" rel="noopener">https://github.com/Baidu-ecom/Jprotobuf-rpc-socket，（貌似是百度出品，代码质量还是有保障的）</a></p>
<p>这个不是本文的重点，暂不详细展开。</p>
<h2 id="言归正传，我们来说Motan怎么实现"><a href="#言归正传，我们来说Motan怎么实现" class="headerlink" title="言归正传，我们来说Motan怎么实现"></a>言归正传，我们来说Motan怎么实现</h2><p>上面说了一堆，貌似跑题了，不过接下来，我们来剖析Motan 的源代码，看Motan是怎么实现这个逻辑的。</p>
<p>直接看源代码，（为了简洁，略掉不相关逻辑代码）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">NettyClient</span> <span class="keyword">extends</span> <span class="title">AbstractPoolClient</span> <span class="keyword">implements</span> <span class="title">StatisticCallback</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 回收过期任务</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(<span class="number">4</span>);</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 异步的request，需要注册callback future</span></span><br><span class="line">	<span class="comment">// 触发remove的操作有： 1) service的返回结果处理。 2) timeout thread cancel</span></span><br><span class="line">	<span class="keyword">protected</span> ConcurrentMap&lt;Long, NettyResponseFuture&gt; callbackMap = <span class="keyword">new</span> ConcurrentHashMap&lt;Long, NettyResponseFuture&gt;();</span><br><span class="line"></span><br><span class="line">	<span class="keyword">private</span> ScheduledFuture&lt;?&gt; timeMonitorFuture = <span class="keyword">null</span>;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">NettyClient</span><span class="params">(URL url)</span> </span>&#123;</span><br><span class="line">			timeMonitorFuture = scheduledExecutor.scheduleWithFixedDelay(</span><br><span class="line">				<span class="keyword">new</span> TimeoutMonitor(<span class="string">"timeout_monitor_"</span> + url.getHost() + <span class="string">"_"</span> + url.getPort()),</span><br><span class="line">				MotanConstants.NETTY_TIMEOUT_TIMER_PERIOD, MotanConstants.NETTY_TIMEOUT_TIMER_PERIOD,</span><br><span class="line">				TimeUnit.MILLISECONDS);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 请求remote service</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * &lt;pre&gt;</span></span><br><span class="line"><span class="comment">	 * 		1)  get connection from pool</span></span><br><span class="line"><span class="comment">	 * 		2)  async requset</span></span><br><span class="line"><span class="comment">	 * 		3)  return connection to pool</span></span><br><span class="line"><span class="comment">	 * 		4)  check if async return response, true: return ResponseFuture;  false: return result</span></span><br><span class="line"><span class="comment">	 * &lt;/pre&gt;</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> request</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> async</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@throws</span> TransportException</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">private</span> Response <span class="title">request</span><span class="params">(Request request, <span class="keyword">boolean</span> async)</span> <span class="keyword">throws</span> TransportException </span>&#123;</span><br><span class="line">		...</span><br><span class="line">		<span class="comment">// async request</span></span><br><span class="line">		response = channel.request(request);</span><br><span class="line">		response = asyncResponse(response, async);</span><br><span class="line">		<span class="keyword">return</span> response;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 初始化 netty clientBootstrap</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initClientBootstrap</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		</span><br><span class="line">		bootstrap.setPipelineFactory(<span class="keyword">new</span> ChannelPipelineFactory() &#123;</span><br><span class="line">			...</span><br><span class="line">			<span class="function"><span class="keyword">public</span> ChannelPipeline <span class="title">getPipeline</span><span class="params">()</span> </span>&#123;</span><br><span class="line">				ChannelPipeline pipeline = Channels.pipeline();</span><br><span class="line">				pipeline.addLast(<span class="string">"decoder"</span>, <span class="keyword">new</span> NettyDecoder(codec, NettyClient.<span class="keyword">this</span>, maxContentLength));</span><br><span class="line">				pipeline.addLast(<span class="string">"encoder"</span>, <span class="keyword">new</span> NettyEncoder(codec, NettyClient.<span class="keyword">this</span>));</span><br><span class="line">				pipeline.addLast(<span class="string">"handler"</span>, <span class="keyword">new</span> NettyChannelHandler(NettyClient.<span class="keyword">this</span>, <span class="keyword">new</span> MessageHandler() &#123;</span><br><span class="line">					<span class="meta">@Override</span></span><br><span class="line">					<span class="function"><span class="keyword">public</span> Object <span class="title">handle</span><span class="params">(Channel channel, Object message)</span> </span>&#123;</span><br><span class="line">						Response response = (Response) message;</span><br><span class="line"></span><br><span class="line">						NettyResponseFuture responseFuture = NettyClient.<span class="keyword">this</span>.removeCallback(response.getRequestId());</span><br><span class="line"></span><br><span class="line">						<span class="keyword">if</span> (responseFuture == <span class="keyword">null</span>) &#123;</span><br><span class="line">							LoggerUtil.warn(</span><br><span class="line">									<span class="string">"NettyClient has response from server, but resonseFuture not exist,  requestId=&#123;&#125;"</span>,</span><br><span class="line">									response.getRequestId());</span><br><span class="line">							<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">						&#125;</span><br><span class="line"></span><br><span class="line">						<span class="keyword">if</span> (response.getException() != <span class="keyword">null</span>) &#123;</span><br><span class="line">							responseFuture.onFailure(response);</span><br><span class="line">						&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">							responseFuture.onSuccess(response);</span><br><span class="line">						&#125;</span><br><span class="line"></span><br><span class="line">						<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;));</span><br><span class="line">				<span class="keyword">return</span> pipeline;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 注册回调的resposne</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * &lt;pre&gt;</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * 		进行最大的请求并发数的控制，如果超过NETTY_CLIENT_MAX_REQUEST的话，那么throw reject exception</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * &lt;/pre&gt;</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@throws</span> MotanServiceException</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> requestId</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> nettyResponseFuture</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">registerCallback</span><span class="params">(<span class="keyword">long</span> requestId, NettyResponseFuture nettyResponseFuture)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (<span class="keyword">this</span>.callbackMap.size() &gt;= MotanConstants.NETTY_CLIENT_MAX_REQUEST) &#123;</span><br><span class="line">			<span class="comment">// reject request, prevent from OutOfMemoryError</span></span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> MotanServiceException(<span class="string">"NettyClient over of max concurrent request, drop request, url: "</span></span><br><span class="line">					+ url.getUri() + <span class="string">" requestId="</span> + requestId, MotanErrorMsgConstant.SERVICE_REJECT);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">this</span>.callbackMap.put(requestId, nettyResponseFuture);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 移除回调的response</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> requestId</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> NettyResponseFuture <span class="title">removeCallback</span><span class="params">(<span class="keyword">long</span> requestId)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> callbackMap.remove(requestId);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 回收超时任务</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@author</span> maijunsheng</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="class"><span class="keyword">class</span> <span class="title">TimeoutMonitor</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">		<span class="keyword">private</span> String name;</span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="title">TimeoutMonitor</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">			<span class="keyword">this</span>.name = name;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">			<span class="keyword">long</span> currentTime = System.currentTimeMillis();</span><br><span class="line">			<span class="keyword">for</span> (Map.Entry&lt;Long, NettyResponseFuture&gt; entry : callbackMap.entrySet()) &#123;</span><br><span class="line">				<span class="keyword">try</span> &#123;</span><br><span class="line">					NettyResponseFuture future = entry.getValue();</span><br><span class="line"></span><br><span class="line">					<span class="keyword">if</span> (future.getCreateTime() + future.getTimeout() &lt; currentTime) &#123;</span><br><span class="line">						<span class="comment">// timeout: remove from callback list, and then cancel</span></span><br><span class="line">						removeCallback(entry.getKey());</span><br><span class="line">						future.cancel();</span><br><span class="line">					&#125; </span><br><span class="line">				&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">					LoggerUtil.error(</span><br><span class="line">							name + <span class="string">" clear timeout future Error: uri="</span> + url.getUri() + <span class="string">" requestId="</span> + entry.getKey(),</span><br><span class="line">							e);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个里面的callbackMap就是存储request上下文的map，（TimeoutMonitor就是清理超时的请求上下文的）发送request请求的时候会调用到下面的方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Response <span class="title">request</span><span class="params">(Request request)</span> <span class="keyword">throws</span> TransportException </span>&#123;</span><br><span class="line"> </span><br><span class="line">  ...</span><br><span class="line">	<span class="keyword">boolean</span> result = writeFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS);</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> (result &amp;&amp; writeFuture.isSuccess()) &#123;</span><br><span class="line">		response.addListener(<span class="keyword">new</span> FutureListener() &#123;</span><br><span class="line">			<span class="meta">@Override</span></span><br><span class="line">			<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">operationComplete</span><span class="params">(Future future)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">				<span class="keyword">if</span> (future.isSuccess() || (future.isDone() &amp;&amp; ExceptionUtil.isBizException(future.getException()))) &#123;</span><br><span class="line">					<span class="comment">// 成功的调用 </span></span><br><span class="line">					nettyClient.resetErrorCount();</span><br><span class="line">				&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">					<span class="comment">// 失败的调用 </span></span><br><span class="line">					nettyClient.incrErrorCount();</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;);</span><br><span class="line">		<span class="comment">// 如果正常情况，就直接返回response</span></span><br><span class="line">		<span class="keyword">return</span> response;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	writeFuture.cancel();</span><br><span class="line">	<span class="comment">// 异常情况 将任务移除</span></span><br><span class="line">	response = <span class="keyword">this</span>.nettyClient.removeCallback(request.getRequestId());</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> (response != <span class="keyword">null</span>) &#123;</span><br><span class="line">		response.cancel();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们可以看到在正常情况下会直接返回response，异常情况下则是直接调用removeCallback(request.getRequestId())清除了callbackMap中的无用request。
接下来我们看正常情况下，motan是在哪里清理callbackMap中内容的？
这个时候我们又需要回到上面的NettyClient中去看NettyChannelHandler了。
收到服务器的返回的response的时候会触发NettyChannelHandler的handle方法，而handle方法中首先就是:
通过消息id，移除callbackMap中的对象。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">NettyResponseFuture responseFuture = NettyClient.<span class="keyword">this</span>.removeCallback(response.getRequestId());</span><br></pre></td></tr></table></figure>
<p>最后，我们看NettyClient中的TimeoutMonitor,它所做的的事情就是定时清理callbackMap超时的request上下文,NettyClient在初始化的时候就初始化了这个timeoutMonitor</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">NettyClient</span><span class="params">(URL url)</span> </span>&#123;</span><br><span class="line">			timeMonitorFuture = scheduledExecutor.scheduleWithFixedDelay(</span><br><span class="line">				<span class="keyword">new</span> TimeoutMonitor(<span class="string">"timeout_monitor_"</span> + url.getHost() + <span class="string">"_"</span> + url.getPort()),</span><br><span class="line">				MotanConstants.NETTY_TIMEOUT_TIMER_PERIOD, MotanConstants.NETTY_TIMEOUT_TIMER_PERIOD,</span><br><span class="line">				TimeUnit.MILLISECONDS);</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
<p>接下来我们总结一下motan中callbackMap的逻辑：</p>
<ul>
<li>client发送request前先将request register到callbackMap中，如果发送前连接异常，则直接remove掉。</li>
<li>客户端收到response后，根据requestId找到对应的request上下文，并移除callbackMap中的对应的对象</li>
<li>对于服务端超时或者其他异常，客户端收不到消息的情况，则通过TimeoutMonitor来定时扫描callbackMap来清理。</li>
</ul>
<p>到这里为止，我们还没讲到motan的异步通知是怎么实现的：
具体实现可以看callbackMap中的NettyResponseFuture对象，它并不是通过java中闭锁CountDownLatch实现，而是用原生的lock.wait(), lock.notifyAll();来实现的。并不算复杂。有兴趣可以直接看源代码。</p>
<h2 id="后记"><a href="#后记" class="headerlink" title="后记"></a>后记</h2><p>异步消息的重点就是在客户端维护一个唯一的消息id，发送前先建立一个消息id和请求request上下文的映射，然后发送request消息到服务端。等收到服务端的response消息后，通过之前建立的映射找到对应的request，并且通过异步地址通知对应request，收到返回消息。</p>
<p>这种要异步通知机制就涉及到<code>callback&amp;CountDownLatch</code>一些相关的知识。</p>
<p>但是要实现一个靠谱的RPC框架，<code>一定要注意存放消息id和请求Request上下文映射的map特殊情况的内存释放问题</code>。而且这个map最好是线程安全的，一般rpc都会用到多线程。</p>
<p>最后，还有值得关注的地方：</p>
<p>实现一个完善的RPC框架，<code>能否有效的各种情况的异常透传到客户端</code>还是一个很重要的议题（用过公司的某个rpc，不管什么异常都是TimeoutException，联调接口时，如果出问题只能跪求别人查日志…），虽然本文没有讨论，但是有兴趣的可以好好研究一下motan在这一块的设计。
不过后续可能也会写对应的文章，好好探讨rpc异常设计和传递。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>大侠劫富济贫啦！</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/images/dempe/20180527112524.jpg" alt="DempeZheng WeChat Pay"/>
        </div>
      
      
    </div>
  </div>


      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016-09-19-motan-spi.html" rel="next" title="Motan源码解读-SPI机制">
                <i class="fa fa-chevron-left"></i> Motan源码解读-SPI机制
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016-09-20-motan-loadbalance.html" rel="prev" title="Motan源码解读-负载均衡">
                Motan源码解读-负载均衡 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="https://avatars3.githubusercontent.com/u/6263631?v=3&s=466"
               alt="DempeZheng" />
          <p class="site-author-name" itemprop="name">DempeZheng</p>
           
              <p class="site-description motion-element" itemprop="description">請更固執，將自己謀生與擅長的事情做到最好</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">68</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">23</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/dempeZheng" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://music.163.com/#/user/home?id=6758793" target="_blank" title="网易云音乐">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  网易云音乐
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/dempe" target="_blank" title="知乎">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  知乎
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              Links
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.wolfbe.com/" title="朗度云" target="_blank">朗度云</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#如何设计RPC异步消息？"><span class="nav-number">1.</span> <span class="nav-text">如何设计RPC异步消息？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#纸上得来终觉浅，我们试着来撸一个"><span class="nav-number">2.</span> <span class="nav-text">纸上得来终觉浅，我们试着来撸一个</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#But，还有一个大bug"><span class="nav-number">3.</span> <span class="nav-text">But，还有一个大bug</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#言归正传，我们来说Motan怎么实现"><span class="nav-number">4.</span> <span class="nav-text">言归正传，我们来说Motan怎么实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#后记"><span class="nav-number">5.</span> <span class="nav-text">后记</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">DempeZheng</span>
</div>



        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  






  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  




	





  





  





  






  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("dhzMp0HdJLWMCrt04bwybWzH-gzGzoHsz", "gH6FmxJiUaVLLRXQDWpkkIVv");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

</body>
</html>
